/**
 * 
 */
package com.williamoneil.charts.client.widget;

import com.google.gwt.user.client.ui.SimplePanel;
import com.williamoneil.charts.client.Charts;
import com.williamoneil.charts.client.controller.ChartController;
import com.williamoneil.charts.client.data.ChartBoundsRect;
import com.williamoneil.charts.client.data.ChartElementsData;
import com.williamoneil.charts.client.util.ChartUtil;

/**
 * @author gudipati
 *
 */
public class ChartWidget {

	private ChartLayer chartLayer = null;
	
	//private ChartElementsData chartElements = null;
	//private yChartBoundsRect chartBounds = null;
	
	private SimplePanel internalPanel = new SimplePanel();
	
	public ChartWidget(int width, int height){
		final ChartBoundsRect chartBounds = new ChartBoundsRect(0, 0, height, width);
		
		internalPanel.setSize("100%", "100%");
				
		chartLayer = new ChartLayer(chartBounds);
		
		internalPanel.add(chartLayer.getCanvas());
		
		chartLayer.getCanvas().setStyleName("chartcanvas");
		chartLayer.getCanvas().getCanvasElement().blur();
	}
	
	/**
	 * @return the internalPanel
	 */
	public SimplePanel getInternalPanel() {
		return internalPanel;
	}
	
	/**
	 * @return the chartLayer
	 */
	public ChartLayer getChartLayer() {
		return chartLayer;
	}
	
	public void resetChartElements(ChartElementsData chartElements) {		
		this.chartLayer.resetData(chartElements);
	}

	public ChartBoundsRect getChartBounds() {
		return chartLayer.getChartBoundsRect(); 
	}
	
	/**
	 * @param chartBounds the chartBounds to set
	 */
	public void resetChartBounds() {
		try {
		final  int height = chartLayer.getCanvas().getOffsetHeight();
		final int width = chartLayer.getCanvas().getOffsetWidth();

		ChartBoundsRect chartBounds = chartLayer.getChartBoundsRect();
		
		if(chartBounds == null || chartBounds.getHeightWithoutScale() != height || chartBounds.getWidthWithoutScale() != width) {
			
			chartBounds = new ChartBoundsRect(chartLayer.getCanvas().getAbsoluteLeft(), chartLayer.getCanvas().getAbsoluteTop(), height, width);
			
			// reset bounds first
			chartLayer.resetChartBounds(chartBounds);
			
			// rest data next
			final ChartElementsData elements = chartLayer.getChartElements();
			if(elements != null) {
				ChartUtil.populateChartElements(elements, ChartController.getInstance().getBenchmarkChart(elements.getPeriodicity()), chartBounds, chartLayer.isLinear(), chartLayer.getTickSpacing());
				resetChartElements(elements);
			}
			
			// draw the chart again
			this.drawChart();
		}
		}catch(Exception ex) {
			Charts.showError(ex);
		}
	}

	public void drawChart() {
		// first clear old drawings
		chartLayer.clearAllCanvas();
				
		// call the trackPrice draw-overlay 
		chartLayer.drawOverlay();
	}
}
